#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<sys/socket.h>
#include<arpa/inet.h>

using namespace std;


class Sock
{
public:
  static int Socket()
  {
    int sock = socket(AF_INET,SOCK_STREAM,0);
    if(sock < 0)
    {
      perror("socket");
      exit(1);
    }
    cout << "创建套接字 success !" << endl;
    return sock;
  }
  static void Bind(int sock,uint16_t port)
  {
      struct sockaddr_in local;
      memset(&local,0,sizeof(local)); // bzero(&local,sizeof(local));
      local.sin_addr.s_addr = INADDR_ANY;
      local.sin_port = htons(port);
      local.sin_family = AF_INET;
      socklen_t len = sizeof(local);
      if(bind(sock,(struct sockaddr*)&local,len) < 0)
      {
        perror("bind");
        exit(2);
      }
      cout <<"Bind Success! " << endl;
  }
  static void Listen(int sock)
  {
    if(listen(sock,5) < 0)
    {
      perror("listen");
      exit(3);
    }
    cout <<"listen Success !" << endl;
  }
  static void Connect(int sock,string ip ,uint16_t port)
  {
     struct sockaddr_in server; 
     bzero(&server,sizeof(server));
     server.sin_family = AF_INET; 
     server.sin_port = htons(port);
     server.sin_addr.s_addr = inet_addr(ip.c_str());
     if(connect(sock,(struct sockaddr*)&server,sizeof(server)) < 0)
     {
       perror("connect");
       exit(4);
     }
     cout << "Connect Success !" << endl;
  }
  static int Accept(int sock)
  {
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    socklen_t len = sizeof(server);
    int fd = accept(sock,(struct sockaddr*)&server,&len);
    if(fd >= 0)
    {
      string ip = inet_ntoa(server.sin_addr);
      uint16_t port = ntohs(server.sin_port);
      cout <<"新连接到来 IP:" << ip << " port " << port << endl; 
      return fd;
    }
    return -1;
  }
};

